var url 		= "http://203.236.20.167:9000/service.pe?";
var authInfo 	= null;
var mailId 	  	= null;
var changeKey 	= null;
var writeType 	= null;
var xmlHandler 	= new SKTXmlHandler;
var reference=1;
var database = new Database();
var content= null;
var title = null;
var name = null;
var ref = null;
var hidRef = null;
var created = null;
var toListDBAr = [];
var ccListDBAr = [];
var bccListDBAr= [];

function init() {
	
//	map_db.put("content",row["content"]);
//	map_db.put("fromInfoName",row["name"]);
//	map_db.put("id", row["id"]);
//	map_db.put("refInfo1", row["ref"]);
//	map_db.put("hideInfo2", row["hidRef"]);
	
	checkTheme();	
	initHandler();
    getSignature();
    //메일쓰기의 종류에 따라 분기한다. reply, replyAll, forward, tempWrite
    authInfo  	= alopexController.parameters["authInfo"];
    mailId 	  	= alopexController.parameters["mailId"];
    changeKey 	= alopexController.parameters["changeKey"];
    writeType 	= alopexController.parameters["mailType"];
    //받는사람의 이름을 보여주되, 발송시 메일주소로 보낸다.
    if(writeType!="tempWrite"){
	    var fromInfoName  = alopexController.parameters["fromInfoName"];
	    var fromInfoEmail = alopexController.parameters["fromInfoEmail"];
	    var toListNames	  = alopexController.parameters["toListNames"];
	    var toListEmails  = alopexController.parameters["toListEmails"];
	    var ccListNames   = alopexController.parameters["ccListNames"];
	    var ccListEmails  = alopexController.parameters["ccListEmails"];
	    var mailTitle 	  = alopexController.parameters["mailTitle"];
	    //alert(fromInfoName+"\n"+fromInfoEmail);
	    toListDBAr = createAr(fromInfoName, fromInfoEmail);
	    ccListDBAr = createAr(toListNames+ccListNames, toListEmails+ccListEmails);
    }
    
//  TextInput List 테스트
     switch(writeType){
    //...
    	case "reply":
    		if(toListDBAr!="undefined"){
    			userWList1.setData(toListDBAr);
//    			userWList1.setOnItemClickHandler(onList1ItemClick);
    		}
    		subject2.setText("Re: " + mailTitle);
    		break;
    		
    	case "replyAll":
    		if(toListDBAr!="undefined"){
    			userWList1.setData(toListDBAr);
//    			userWList1.setOnItemClickHandler(onList2ItemClick);
    			//alert(toListNames);
    			//alert(ccListNames);
    		}
    		
    		if(ccListDBAr!="undefined"){
    			userWList2.setData(ccListDBAr);
//    			userWList2.setOnItemClickHandler(onList3ItemClick);
    		}
    		
    		subject2.setText("Re: " + mailTitle);
    		//alert(writeType);
    		break;
    		
    	case "forward":
    		subject2.setText("Fwd: " + mailTitle);
    		break;
    		
    	case "tempWrite":
    		tempDBbinding();
    		break;
    		
    	default:
    		break;
    
    }
}

//nameString,mailString,
function createAr(str1, str2){
	//...받는이 정보 및 배열관리
	if(str2!=undefined){
		var toListNamesAr   = str1.split(';');
		var toListEmailsAr  = str2.split(';');
		var tmpArr			= new Array();	//받는이 이름, 이메일 배열
		
		for(var k=0; k<toListEmailsAr.length; k++){
			if(toListEmailsAr[k]==""||toListEmailsAr[k]==undefined||toListEmailsAr[k]=="undefined"){
				toListNamesAr.remove(k);
				toListEmailsAr.remove(k); 
			}
		};
		
		for(var k=0; k<toListEmailsAr.length; k++){
			var tmpToListAr = new Map();
			tmpToListAr.put("UserName",toListNamesAr[k]);
			tmpToListAr.put("UserMail",toListEmailsAr[k]);
			tmpArr.push(tmpToListAr);
		};
	}
	return tmpArr;
}

//listComponent의 이름과 이메일을 string으로 변환하여 return [nameString,mailString]
function createFromArToString(listComponent){
	var tmpDataList = listComponent.getData();
	var tmpUserNameString = "";
	var tmpUserMailString = "";
    for(var i=0;i<tmpDataList.length;i++){
    	tmpUserNameString += tmpDataList[i].get("UserName") + ";";
    	tmpUserMailString += tmpDataList[i].get("UserMail") + ";";
	}
    return [tmpUserNameString,tmpUserMailString];
}

//Array.prototype.remove = function(object) {
//	alert(typeof(object));
//	  var from = this.indexOf(object);
//	  var to = from;
//	  alert("to:"+to+ ", from:"+from+", length: "+this.length)
//	  var rest = this.slice((to || from) + 1 || this.length);
//	  this.length = from < 0 ? this.length + from : from;
//	  return this.push.apply(this, rest);
//};

Array.prototype.remove = function(from, to) {
	  var rest = this.slice((to || from) + 1 || this.length);
	  this.length = from < 0 ? this.length + from : from;
	  return this.push.apply(this, rest);
};

function initHandler(){
	userWList1.setOnItemClickHandler(onList1ItemClick);
	userWList2.setOnItemClickHandler(onList2ItemClick);
	userWList3.setOnItemClickHandler(onList3ItemClick);
	
	optBtnw1.setOnClickHandler(tmpSave);
	optBtnw2.setOnClickHandler(compCnl);
	optBtnw3.setOnClickHandler(mailSend);
	    
	userBtn1.setOnClickHandler(recieverAdd);
	userBtn2.setOnClickHandler(recieverAdd);
	userBtn3.setOnClickHandler(recieverAdd);
	
    writePanel6.setOnClickHandler(referencePanelHiddenChange);
 
}

//...임시보관함 아이템 클릭시 데이터 뿌려준다.
function tempDBbinding(){
	
	var DB_ID = alopexController.parameters["db_id"];
	var DB_CONTENT= alopexController.parameters["db_content"];
	var DB_NAME= alopexController.parameters["db_name"];
	var DB_TITLE= alopexController.parameters["db_title"];
	var DB_REF = alopexController.parameters["db_ref"];
	var DB_HIDREF = alopexController.parameters["db_hidRef"];
	
	//alert(DB_NAME);
	//제목, 본문
	if (DB_TITLE=="제목없음" || DB_TITLE == null ||DB_TITLE==" " ){
		subject2.setText("");
	}else{
		subject2.setText(DB_TITLE);
	}
	
	if (DB_CONTENT=="" || DB_CONTENT == null){
		textarea.setText("");
	}else{
		textarea.setText(DB_CONTENT);
	}
	
	//받는이, 참조, 숨은참조.
    toListDBAr = createAr(DB_NAME, DB_NAME);
    ccListDBAr = createAr(DB_REF, DB_REF);
    bccListDBAr = createAr(DB_HIDREF, DB_HIDREF);
    
	if (DB_NAME!="" && DB_NAME!=null && DB_NAME!="undefined"){
		userWList1.setData(toListDBAr);
//		userWList1.setOnItemClickHandler(onListItemClick);
	}
	
	if (DB_REF!="" && DB_REF!=null && DB_REF!="undefined"){
		userWList2.setData(ccListDBAr);
//		userWList2.setOnItemClickHandler(onListItemClick);
	}
	
	if (DB_HIDREF!="" && DB_HIDREF!=null && DB_HIDREF!="undefined"){
		userWList3.setData(bccListDBAr);
//		userWList3.setOnItemClickHandler(onListItemClick);
	}
}
//...
function onList1ItemClick(e){
//	alert("id : " + parent.id + ", index : " + e.currentTarget.index);
	var tmpIndex = e.currentTarget.index;
	toListDBAr.remove(tmpIndex);
	userWList1.setData(toListDBAr);
	userWList1.refresh();
}

function onList2ItemClick(e){
//	alert("2>>> id : " + parent.id + ", index : " + e.currentTarget.index);
	var tmpIndex = e.currentTarget.index;
	ccListDBAr.remove(tmpIndex);
	userWList2.setData(ccListDBAr);
	userWList2.refresh();
}

function onList3ItemClick(e){
//	alert("id : " + parent.id + ", index : " + e.currentTarget.index);
	var tmpIndex = e.currentTarget.index;
	bccListDBAr.remove(tmpIndex);
	userWList3.setData(bccListDBAr);
	userWList3.refresh();
}

//구성원검색앱 호출하거나 수신인추가
function recieverAdd(e){

	var clickBtn = e.target.id;
	
	switch(clickBtn){
	
		case "userBtn1":
			nativeUI.setContextMenuItem("수신인추가", select1RecieverAdd);
			break;
			
		case "userBtn2":
			nativeUI.setContextMenuItem("수신인추가", select2RecieverAdd);
			break;
			
		case "userBtn3":
			nativeUI.setContextMenuItem("수신인추가", select3RecieverAdd);
			break;
	}
	
	nativeUI.setContextMenuItem("구성원검색", selectContactApp);
	nativeUI.showContextMenu();
}

function select1RecieverAdd(){
	var arg = prompt("추가하실 이메일 주소를 입력하세요.","");
	var tmpToListAr = new Map();
	tmpToListAr.put("UserName",arg);
	tmpToListAr.put("UserMail",arg);
	toListDBAr.push(tmpToListAr);
	userWList1.setData(toListDBAr);
}
function select2RecieverAdd(){
	var arg = prompt("추가하실 이메일 주소를 입력하세요.","");
	var tmpToListAr = new Map();
	tmpToListAr.put("UserName",arg);
	tmpToListAr.put("UserMail",arg);
	ccListDBAr.push(tmpToListAr);
	userWList2.setData(ccListDBAr);
}
function select3RecieverAdd(){
	var arg = prompt("추가하실 이메일 주소를 입력하세요.","");
	var tmpToListAr = new Map();
	tmpToListAr.put("UserName",arg);
	tmpToListAr.put("UserMail",arg);
	bccListDBAr.push(tmpToListAr);
	userWList3.setData(bccListDBAr);
}

function selectContactApp(){
	alert('구성원검색 APP 연동 예정입니다.');
}

function getSignature(){
	
	var signature = preference.getString("signature");
    document.getElementById('signTxtarea').value = signature; 
}

function referencePanelHiddenChange(){
	
	if(reference==1){
		document.getElementById("writePanel5").style.display = "block";
		document.getElementById("writePanel2").style.display = "block";
		document.getElementById("writePanel6").style.display = "none";
		reference=0;
		}

	else if(reference==0){
		document.getElementById("writePanel6").style.display = "block";
		document.getElementById("writePanel2").style.display = "none";
		document.getElementById("writePanel5").style.display = "none";
		reference=1;
		}
}

//임시보관함 DB저장 하는 방법 
function tmpSave() {

	database.open("NgmsMA");
//	var sqlStr = null;
//	sqlStr="CREATE TABLE ngms_ma_table(id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, title TEXT  null, name TEXT null, content TEXT null, ref TEXT null, hidRef TEXT null, created TEXT null);";
//	
//	try {
//		database.executeUpdate(sqlStr, null);
//	} catch(e) {
//		database.error = e;
//	}
//
//	if(database.error == null){
//		
//		log.log("Creating table(name : ngms_ma_table) successful");
//	}else{
//		log.log(database.error);
//	}
		
//	insertHandler();
//	//임시보관함에 저장
//	function insertHandler() {
		
		//받는이
		var toAr = createFromArToString(userWList1);
		var name = toAr[1];
		if (name == "" || name == undefined)
			name = "";
		
		//참조
		var toCc = createFromArToString(userWList2);
		var ref  = toCc[1];
		if (ref  == "" || ref == undefined)
			ref  = "";
		
		//숨은참조
		var toBcc  = createFromArToString(userWList3);
		var hidRef = toBcc[1];
		if (hidRef =="" || hidRef == undefined)
			hidRef = "";
		
		//제목
		var title = subject2.getText();
		if (title == "" || title == undefined)
			title ="";
		
		//본문
		var content    = textarea.getText();
		if ( content == "" || content == undefined)
			content = "";
		
		//time
		var currentDate    = new Date();
		var	tempcreatedY   = leadingZeros(currentDate.getFullYear(),4);
		var tempcreatedM   = leadingZeros(currentDate.getMonth()+1,2);
		var tempcreatedD   = leadingZeros(currentDate.getDate(),2);
		var tempcreatedH   = leadingZeros(currentDate.getHours(),2);
		var tempcreatedMin = leadingZeros(currentDate.getMinutes(),2);
		var created    	   = (tempcreatedY + "" + tempcreatedM + "" + tempcreatedD + "" + tempcreatedH + "" +tempcreatedMin);

		var sqlStr = null;
		sqlStr = "INSERT INTO ngms_ma_table (title, name, content, ref, hidRef, created) VALUES(?, ?, ?, ?, ?, ?);";

		try {
			database.executeUpdate(sqlStr, [title, name, content, ref, hidRef, created]);
		} catch(e) {
			database.error = e;
			alert(e);
		}

		if(database.error == null)
			alert("저장되었습니다.");
		else
			alert("임시보관함 저장오류 : \n" + database.error);
//	}
////	selectHandler();
////	function selectHandler() {
//		var sqlStr = null;
//		
//		sqlStr = "SELECT * FROM ngms_ma_table order by id;";
//
//		//database.send(sqlStr, [content]);
//		//list4.setData(dataset);
//		try {
//
//			database.executeQuery(sqlStr, selectSuccessHandler, selectErrorHandler);
//			
//		} catch(e) {
//			database.error = e;
//		}
//		
//		if(database.error != null)
//			log.log("Selecting data(name : ngms_ma_table) successful");
//		else
//			log.log("Selecting data error : " + database.error);
////	}
	
//	selectSuccessHandler(transaction, results);
	
	//database.onDatabaseSuccessHandler(transaction, results);
	//database.parse(results, arr);	
	//alopexController.navigate("Mail_List");
		alopexController.goStartPage();
}


function compCnl() {
	//alert('작성 취소 되었습니다.');
	alopexController.navigateWithParameters("Mail_List", {"authInfo" : authInfo});
}

function mailSend() {

//	nativeUI.showProgressDialog();

	var tmpParams = new Object();
		
    switch(writeType){
    
    	case "reply":
    		tmpParams["function"] 	= "COMMON_MAIL_REPLY";
    		tmpParams["ID"] 		=  URLEncode(mailId);
    		tmpParams["CHANGEKEY"] 	=  URLEncode(changeKey);
    		break;
    		
    	case "replyAll":
    		tmpParams["function"] 	= "COMMON_MAIL_REPLY";
    		tmpParams["ID"] 		=  URLEncode(mailId);
    		tmpParams["CHANGEKEY"] 	=  URLEncode(changeKey);
    		break;
    		
    	case "forward":
    		tmpParams["function"] 	= "COMMON_MAIL_FORWARD";
    		tmpParams["ID"] 		=  URLEncode(mailId);
    		tmpParams["CHANGEKEY"] 	=  URLEncode(changeKey);
    		break;
    		
    	case "tempWrite":
    		//tempDBbinding();
    		tmpParams["function"] 	= "COMMON_MAIL_SEND";
    		break;
    		
    	default:
    		tmpParams["function"] 	= "COMMON_MAIL_SEND";
    		break;
    
    }
	
	//... 받는이 리스트를 다시 한줄로 만들기
    
    //alert(tmpDataList[0].get("UserName"));
	var toAr = createFromArToString(userWList1);
	if(toAr!=","){
		
		//name=toAr[0],mail=toAr[1]
		//공백없애기 .replace(/\s/g,'')
		tmpParams["to"] = URLEncode(toAr[1]);
		
		var toCc = createFromArToString(userWList2);
		if(toCc!=","){tmpParams["cc"] = URLEncode(toCc[1])};
		
		var toBcc = createFromArToString(userWList3);
		if(toBcc!=","){tmpParams["bcc"] = URLEncode(toBcc[1])};
		
		tmpParams["SUBJECT"] 	= encodeURIComponent(subject2.getText());
		
		//본문 관련 작업
		var content  = textarea.getText();
		var content2 = signTxtarea.getText();
		
		//content  = content.replace("\n","<br>");
		content  = content.split("\n").join("<br>");
		content2 = content2.split("\n").join("<br>");
		
		tmpParams["bodyType"] 	= URLEncode("HTML");
		tmpParams["BODY"] 		= encodeURIComponent(content +"<br><br>================================<br><br>" + content2);
		tmpParams["sendType"] 	= URLEncode("SEND");
		
		var requestXml = xmlHandler.make(tmpParams);
		log.log("request : " + url + authInfo + "\n params : \n" + requestXml );
		//alert("request : " + url + authInfo + "\n params : \n" + requestXml );
		
		if(tmpParams["BODY"]== null || tmpParams["BODY"]== undefined ||tmpParams["BODY"]==""){
			if(confirm('본문 내용이 없습니다.\n발송하시겠습니까?')){
				tmpParams["BODY"] 		= encodeURIComponent(" ");
				http.request( url + authInfo, "POST", tmpParams, getMailSendCallback, failureCallback );
			
			}
		}else{
			http.request( url + authInfo, "POST", tmpParams, getMailSendCallback, failureCallback );
		}
		
	}else{
		alert("수신자를 지정해주세요.");
	}
	
}

function getMailSendCallback(){
	
	var xmlStr = http.response;	
	log.log("MailDel SuccessResponseXml :: \n" + xmlStr);
	//alert("MailDel SuccessResponseXml :: \n" + xmlStr);
	nativeUI.dismissProgressDialog();
	
	var tmpxml = (new DOMParser()).parseFromString(xmlStr, "text/xml");
	var result = tmpxml.getElementsByTagName("result")[0].firstChild.nodeValue;
	var resultMessage = tmpxml.getElementsByTagName("resultMessage")[0].firstChild.nodeValue;
	if(result == "1000"){
		alert('메일이 발송되었습니다 .');
		alopexController.navigateWithParameters("Mail_List", {"authInfo" : authInfo});
	}else {
		if( confirm("처리에러\n Result Code : " + result + "\nresultMessage : \n" + resultMessage + "\n\n재시도 하시겠습니까?")){
			init();
		}
	}
	
}

function failureCallback() {
	log.error("Http Error:" + http.error);
	nativeUI.dismissProgressDialog();
	
	tmpSave();
	alert("통신 문제로 임시저장 되었습니다. \n에러코드 : \n" + http.error );
	
}

function leadingZeros(n, digits) {
	  var zero = '';
	  n = n.toString();

	  if (n.length < digits) {
	    for (i = 0; i < digits - n.length; i++)
	      zero += '0';
	  }
	  return zero + n;
}

function selectSuccessHandler(transaction, results) {

	try {
		var rows = results.rows;
		var row = null;
		
		for(var i = 0; i < rows.length; i++) {
			row = rows.item(i);
			
	//alert("row number : " + i + "\nid : " + row["id"] + "\ntitle : " + row["title"] + "\nname : " + row["name"] + "\ncontent : " + row["content"] + "\nref : " + row["reff"] + "\nhidRef : " + row["hidRef"]+ "\ncreated : " + row["created"]);
		}
	} catch(e) {
		alert("selectSuccessHandler error: " + e);
	}
	alert('임시 보관함에 저장되었습니다.');
	goList();
	
}
function goList(){
	
	alopexController.navigateWithParameters("Mail_List", {"authInfo" : authInfo});
    
}
function selectErrorHandler(transaction, error) {

	alert("selectErrorHandler : " + error);
}



function checkTheme(){
	
	var selectTheme = preference.getString("theme");
	
	if ( selectTheme == "black" ){
		document.getElementById("themePanel").className = "themePanel_b";
		
	} else if ( selectTheme == "white" ){
		document.getElementById("themePanel").className = "themePanel_w";
		
	} 
	
}

//이메일 형식체크 
function CheckMailAddress(strMail) { 
   /** 체크사항 
     - @가 2개이상일 경우 
     - .이 붙어서 나오는 경우 
     -  @.나  .@이 존재하는 경우 
     - 맨처음이.인 경우 
     - @이전에 하나이상의 문자가 있어야 함 
     - @가 하나있어야 함 
     - Domain명에 .이 하나 이상 있어야 함 
     - Domain명의 마지막 문자는 영문자 2~4개이어야 함 **/ 

    var check1 = /(@.*@)|(\.\.)|(@\.)|(\.@)|(^\.)/;  

    var check2 = /^[a-zA-Z0-9\-\.\_]+\@[a-zA-Z0-9\-\.]+\.([a-zA-Z]{2,4})$/; 
     
    if ( !check1.test(strMail) && check2.test(strMail) ) { 
        return true; 
    } else { 
        return false; 
    } 
}

//GMP 서버에 쿼리스트링으로 전달전 ID만 Encode하여 전달
function URLEncode (clearString) {
	  var output = '';
	  var x = 0;
	  clearString = clearString.toString();
	  var regex = /(^[a-zA-Z0-9_.]*)/;
	  while (x < clearString.length) {
	    var match = regex.exec(clearString.substr(x));
	    if (match != null && match.length > 1 && match[1] != '') {
	    output += match[1];
	      x += match[1].length;
	    } else {
	      if (clearString[x] == ' ')
	        output += '+';
	      else {
	        var charCode = clearString.charCodeAt(x);
	        var hexVal = charCode.toString(16);
	        output += '%' + hexVal.toUpperCase();
	      }
	      x++;
	    }
	  }
	  return output;
}